import  torch
import matplotlib.pyplot as plt
import  pandas as pd
import numpy as np
from torch import nn
'''数据预处理'''
plt.rcParams['font.family'] = ['Microsoft YaHei']
plt.rcParams['font.sans-serif'] = ['SimHei']
data=pd.read_csv('credit-a.csv',header=None)
print(data)
X=data.iloc[:,:-1]
Y=data.iloc[:,-1].replace(-1,0)
X=torch.from_numpy(X.values).type(torch.float32)
Y=torch.from_numpy(Y.values.reshape(-1,1)).type(torch.float32)

'''创建模型'''
model=nn.Sequential(
    nn.Linear(15,1),
    nn.Sigmoid()
)
'''初始化损失函数'''
loss_fn=nn.BCELoss()

'''优化函数'''
optimizer=torch.optim.Adam(model.parameters(),lr=0.005)

'''训练'''
batches=16
number_of_batch=653//16
epoches=1000
for epoch in range(epoches):
    for batch in range(number_of_batch):
        start=batch*batches
        end=start+batches
        x=X[start:end]
        y=Y[start:end]
        y_pre=model(x)
        loss=loss_fn(y_pre,y)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
print(model.state_dict())
predication=((model(X).data.numpy()>0.5).astype('int')==Y.numpy()).mean()
print("模型准确率:{predication}".format(predication=predication))
